import axios from 'axios'
import { showToast, showLoadingToast, closeToast } from 'vant'
import router from '@/router'
import 'vant/es/toast/style'
import { useTokenStore } from '@/stores/index'
const tokenStore = useTokenStore()

// 创建axios实例
const request = axios.create({
  baseURL: '/api/v1.0',
  timeout: 15000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 显示loading
    if (!config.hideLoading) {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
        duration: 0,
      })
    }

    // 从localStorage获取token
    const token = window.localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }

    return config
  },
  (error) => {
    closeToast()
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    closeToast()
    const res = response.data

    // 根据自定义错误码判断请求是否成功
    if (res.code === 1) {
      // 成功返回解析后的数据
      return res.data
    } else {
      // 处理错误
      handleError(res)
      return Promise.reject(res)
    }
  },
  (error) => {
    closeToast()
    handleError(error.response)
    return Promise.reject(error)
  },
)

// 错误处理函数
function handleError(error) {
  if (!error) {
    showToast('网络异常，请稍后重试')
    return
  }

  const status = error.status
  const message = error.data.message

  switch (status) {
    case 401:
      // token过期或未登录
      showToast(message || '请重新登录')
      tokenStore.clearToken()
      router.push('/login')
      break
    case 403:
      showToast(message || '没有权限')
      break
    case 404:
      showToast(message || '请求的资源不存在')
      break
    case 500:
      showToast(message || '服务器错误')
      break
    default:
      showToast(message || '网络异常，请稍后重试')
  }
}

// 封装请求方法
const http = {
  get(url, params, query, config = {}) {
    return request({
      method: 'get',
      url,
      params,
      query,
      ...config,
    })
  },

  post(url, data, config = {}) {
    return request({
      method: 'post',
      url,
      data,
      ...config,
    })
  },

  put(url, data, config = {}) {
    return request({
      method: 'put',
      url,
      data,
      ...config,
    })
  },

  delete(url, data, config = {}) {
    return request({
      method: 'delete',
      url,
      data,
      ...config,
    })
  },

  // 上传文件
  upload(url, file, config = {}) {
    const formData = new FormData()
    formData.append('file', file)

    return request({
      method: 'post',
      url,
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      ...config,
    })
  },

  // 下载文件
  download(url, params, config = {}) {
    return request({
      method: 'get',
      url,
      params,
      responseType: 'blob',
      ...config,
    })
  },
}

export default http
